package com.example.petproject.controller;

import com.example.petproject.entity.model.UmsUser;
import com.example.petproject.entity.vo.PreSubmitVO;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.entity.vo.ReturnVO;
import com.example.petproject.service.OmsOrderService;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.PetUmsUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 包名称：com.example.petproject.controller
 * 类名称：OmsOrderController
 * 类描述：订单控制器
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月23日 13:35
 **/
@RestController
@RequestMapping("/oms/order")
public class OmsOrderController {

    private static final Logger log = LoggerFactory.getLogger(OmsOrderController.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private OmsOrderService omsOrderService;

    @PostMapping("/preSubmit")
    public ReturnVO<?> preSubmit(@RequestBody Map<String, List<Map<String,Long>>> body, @RequestHeader(value = "Token",required = false)String token){
        if (ObjectUtils.isEmpty(token)) {
            return ReturnVO.error(ReturnStatusEnum.AUTH_TOKEN_EMPTY);
        }
        //生成token redis key
        String tokenKey = PetUmsUtils.generateTokenRedisKey(token);
        String userStr = stringRedisTemplate.opsForValue().get(tokenKey);
        if (ObjectUtils.isEmpty(userStr)) {
            return ReturnVO.error(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
        }
        //反序列化用户
        try {
            UmsUser umsUser = ObjectMapperUtils.stringToObj(userStr, UmsUser.class);
            PreSubmitVO preSubmitVO = omsOrderService.preSubmit(body, umsUser.getId());
            return ReturnVO.ok(preSubmitVO);
        } catch (JsonProcessingException e) {
            log.error("反序列化用户信息异常，{}",e.getMessage());
            return ReturnVO.error(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }
}
